import { Icon, useCall } from '@/components';
import { useSelector, useUpdater } from '@/components/StateProvider';
import { Button, Tree } from 'antd';
import React, { useRef } from 'react';
import { createItem } from './shared';

function DiseaseTree() {
  const treeList = useSelector((v) => v?.treeList ?? []);
  const treeRef = useRef();
  const selectedKeys = useSelector((v) => [v?.currentKey].filter((t) => t && t !== '0'));
  const expandedKeys = useSelector((v) => v?.expandedKeys ?? []);
  const update = useUpdater();

  const onSelect = useCall((selectedKeys) => {
    // console.log('eeeee')
    update({ currentKey: selectedKeys[0] });
  });
  const onExpand = useCall((expandedKeys) => {
    update({ expandedKeys });
  });

  const onAddRoot = useCall(() => {
    update((v) => {
      const treeList = v?.treeList ?? [];
      const expandedKeys = v?.expandedKeys ?? [];
      const newItem = createItem('diseaseType');
      newItem.children.push(createItem('diseaseName', newItem.key));
      return {
        treeList: treeList.concat(newItem),
        currentKey: newItem.key,
        expandedKeys: expandedKeys.concat(newItem.key),
      };
    });
  });

  return (
    <>
      <Tree
        ref={treeRef}
        treeData={treeList}
        blockNode
        selectedKeys={selectedKeys}
        expandedKeys={expandedKeys}
        onSelect={onSelect}
        onExpand={onExpand}
      />
      <Button size='small' icon={<Icon type='plus' />} type='text' onClick={onAddRoot}>
        添加根节点
      </Button>
    </>
  );
}

export default DiseaseTree;
